// pages/index/index.js
const url = getApp();
const QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
const wxMap = new QQMapWX({
  key: 'AB3BZ-QEI6J-7SAFK-FV2J4-YEAR7-C7FYZ' // 必填
});
Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseUrl: '',
    banners:[], 
    partTList:[],
    addressDetail:[],
    showIndex:0,
    jobtype:[],
    quyu:[],
    gongzi:[],
    clickId:0,
    searchValue:0,
    date:'',
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 1500,
    model:true,
    textTop:"选择",
    diqu:'',

    text: '',
    marqueePace: 1,//滚动速度
    marqueeDistance: 0,//初始滚动距离
    marqueeDistance2: 0,
    marquee2copy_status: false,
    marquee2_margin: 60,
    size: 14,
    orientation: 'left',//滚动方向
    marqueeinterval: 20 // 时间间隔

  },
  searchpaettiem: function(){
    
    var accesstoken = wx.getStorageSync('accesstoken')
    var flag = this.data.showIndex
    var key,value;
    value = this.data.searchValue
    if(flag == 1){
      wx.request({
        url: 'https://api.tianlala.com.cn/part-times', // 仅为示例，并非真实的接口地址
        header: {
          'content-type': 'application/json', // 默认值
          'Authorization': accesstoken
        },
        method: 'GET',
        data: {
          'Search[ad_code]': value
        },
        success: (res) => {
          console.log(res, '搜索结果成功')
          if (res.data.length == 0) {
            wx.showToast({
              title: '搜索为空',
            })
          } else {
            this.setData({
              partTList: res.data,
              showIndex: 0
            })
          }
        },
        fail: (res) => {
          console.log(res, '失败')
        }
      })
    }else if(flag == 2){
      wx.request({
        url: 'https://api.tianlala.com.cn/part-times', // 仅为示例，并非真实的接口地址
        header: {
          'content-type': 'application/json', // 默认值
          'Authorization': accesstoken
        },
        method: 'GET',
        data: {
          'Search[job_type]': value
        },
        success: (res) => {
          console.log(res, '搜索结果成功')
          if (res.data.length == 0) {
            wx.showToast({
              title: '搜索为空',
            })
          } else {
            this.setData({
              partTList: res.data,
              showIndex: 0
            })
          }
        },
        fail: (res) => {
          console.log(res, '失败')
        }
      })
    } else if (flag == 3) {
      wx.request({
        url: 'https://api.tianlala.com.cn/part-times', // 仅为示例，并非真实的接口地址
        header: {
          'content-type': 'application/json', // 默认值
          'Authorization': accesstoken
        },
        method: 'GET',
        data: {
          'Search[salary]': value
        },
        success: (res) => {
          console.log(res, '搜索结果成功')
          if(res.data.length == 0){
            wx.showToast({
              title: '搜索为空',
            })
          }else{
            this.setData({
              partTList: res.data,
              showIndex: 0
            })
          }

          
        },
        fail: (res) => {
          console.log(res, '失败')
        }
      })
    } else if (flag == 4) {
      wx.request({
        url: 'https://api.tianlala.com.cn/part-times', // 仅为示例，并非真实的接口地址
        header: {
          'content-type': 'application/json', // 默认值
          'Authorization': accesstoken
        },
        method: 'GET',
        data: {
          'Search[time]': value
        },
        success: (res) => {
          console.log(res, '搜索结果成功')
          if (res.data.length == 0) {
            wx.showToast({
              title: '搜索为空',
            })
          } else {
            this.setData({
              partTList: res.data,
              showIndex: 0
            })
          }
        },
        fail: (res) => {
          console.log(res, '失败')
        }
      })
    }


  },
  bindDateChange:function(e){
    console.log(e.detail.value)
    var date = e.detail.value;
    // console.log(date)
    // var date = '2015-03-05 17:59';
    // date = date.substring(0, 15);
    date = date.replace(/-/g, '/');
    var timestamp = new Date(date).getTime() / 1000;
    this.setData({
      date: e.detail.value,
      searchValue: timestamp
    })
  },
  setinfo: function (e){
    // console.log(e.currentTarget.dataset)
    var flag = this.data.showIndex
    if(flag == 2){
      this.setData({
        clickId: e.currentTarget.dataset.id,
        searchValue: e.currentTarget.dataset.id
      })
    }else{
      this.setData({
        clickId: e.currentTarget.dataset.id,
        searchValue: e.currentTarget.dataset.value
      })
    }

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      baseUrl: url.baseUrl
    })
    this.getBanners('index')
    this.getPartTime()
    this.gettxt()
    this.getJobTypes()
    this.getSearchOptions()

  },
  getJobTypes: function () {
    var accesstoken = wx.getStorageSync('accesstoken')
    wx.request({
      url: 'https://api.tianlala.com.cn/job-types/job', // 仅为示例，并非真实的接口地址
      header: {
        'content-type': 'application/json', // 默认值
        'Authorization': accesstoken
      },
      method: 'GET',
      data: {
      },
      success: (res) => {
        console.log(res, '兼职类型成功')
        this.setData({
          jobtype: res.data
        })
      },
      fail: (res) => {
        console.log(res, '失败');
        wx.navigateTo({
          url: '/pages/login/login',
        })
      }
    })
  },
  getSearchOptions: function () {
    var accesstoken = wx.getStorageSync('accesstoken')
    wx.request({
      url: 'https://api.tianlala.com.cn/search-options', // 仅为示例，并非真实的接口地址
      header: {
        'content-type': 'application/json', // 默认值
        'Authorization': accesstoken
      },
      method: 'GET',
      data: {
      },
      success: (res) => {
        console.log(res, '搜索类型成功')
        this.setData({
          quyu: res.data['3']['0'],
          gongzi: res.data['4']['0']
        })
      },
      fail: (res) => {
        console.log(res, '失败');
        wx.navigateTo({
          url: '/pages/login/login',
        })
      }
    })
  },
  gettxt: function () {
    var accesstoken = wx.getStorageSync('accesstoken')
    wx.request({
      url: 'https://api.tianlala.com.cn/settings', // 仅为示例，并非真实的接口地址
      header: {
        'content-type': 'application/json', // 默认值
        'Authorization': accesstoken
      },
      method: 'GET',
      data: {
      },
      success: (res) => {
        console.log(res, '滚动字幕')
        this.setData({
          text: res.data[28].value
        })
        var vm = this;
        var length = vm.data.text.length * vm.data.size;//文字长度
        var windowWidth = wx.getSystemInfoSync().windowWidth;// 屏幕宽度
        vm.setData({
          length: length,
          windowWidth: windowWidth,
          marquee2_margin: length < windowWidth ? windowWidth - length : vm.data.marquee2_margin//当文字长度小于屏幕长度时，需要增加补白
        });
        // vm.run1();// 水平一行字滚动完了再按照原来的方向滚动
      },
      fail: (res) => {
        console.log(res, '失败');
        wx.navigateTo({
          url: '/pages/login/login',
        })
      }
    })
  },
  getPartTime:function(){
    var accesstoken = wx.getStorageSync('accesstoken')
    wx.request({
      url: 'https://api.tianlala.com.cn/part-times', // 仅为示例，并非真实的接口地址
      header: {
        'content-type': 'application/json', // 默认值
        'Authorization': accesstoken
      },
      method: 'GET',
      data: {
      },
      success: (res) => {
        console.log(res, '全部兼职 成功')
        // if (res.statusCode == 401){
        //   wx.clearStorage({
        //     success:()=>{
        //       wx.navigateTo({
        //         url: '/pages/login/login',
        //       })
        //     }
        //   }) 
        // }
        this.setData({
          partTList: res.data
        })
      },
      fail: (res) => {
        console.log(res, '失败');
        wx.navigateTo({
          url: '/pages/login/login',
        })
      }
    })
  },
  getBanners: function (type){
    var accesstoken = wx.getStorageSync('accesstoken')
    wx.request({
      url: 'https://api.tianlala.com.cn/banners/' + type, // 仅为示例，并非真实的接口地址
      header: {
        'content-type': 'application/json', // 默认值
        'Authorization': accesstoken
      },
      method: 'GET',
      data: {
      },
      success: (res) => {
        console.log(res, 'banner成功')
        this.setData({
          banners: res.data
        })
      },
      fail: (res) => {
        console.log(res, '失败');
        wx.navigateTo({
          url: '/pages/login/login',
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    // 获取小程序更新机制兼容
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager()
      updateManager.onCheckForUpdate(function (res) {
        // 请求完新版本信息的回调
        console.log("是否有更新？", res.hasUpdate);
        if (res.hasUpdate) {
          updateManager.onUpdateReady(function () {
            wx.showModal({
              title: '更新提示',
              content: '新版本已经准备好，是否重启应用？',
              success: function (res) {
                if (res.confirm) {
                  // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                  updateManager.applyUpdate()
                }
              }
            })
          })
          updateManager.onUpdateFailed(function () {
            // 新的版本下载失败
            wx.showModal({
              title: '已经有新版本了哟~',
              content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
            })
          })
        }
      })
    } else {
      // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }

    wx.checkSession({
      success:()=>{
        //session_key 未过期，并且在本生命周期一直有效
        console.log('未过期')
        //判断用户是否授权
        wx.getSetting({
          success: (data) => {
            // console.log(data);
            if (data.authSetting['scope.userInfo']) {
              //用户已经授权
              //获取用户登录信息
              var value = wx.getStorageSync('userInfo')
              //是否有信息
              if (!value.nickName) {
                //没有用户信息
                wx.showToast({
                  title: '本地存储信息失败',
                  icon:'none',
                  duration:1000
                })
                //重新登录
                wx.clearStorageSync();
                wx.navigateTo({
                  url: '/pages/login/login',
                })
              } else {
                
              }
            } else {
              //用户未授权
              //重新登录
              wx.clearStorageSync();
              wx.navigateTo({
                url: '/pages/login/login',
              })
            }
          }
        });
      },
      fail() {
        // session_key 已经失效，需要重新执行登录流程
        //重新登录
        wx.clearStorageSync();
        wx.navigateTo({
          url: '/pages/login/login',
        })
      }
    })
    this.onLoad()

  },
  run1: function () {
    var vm = this;
    var interval = setInterval(function () {
      if (-vm.data.marqueeDistance < vm.data.length) {
        vm.setData({
          marqueeDistance: vm.data.marqueeDistance - vm.data.marqueePace,
        });
      } else {
        clearInterval(interval);
        vm.setData({
          marqueeDistance: vm.data.windowWidth
        });
        vm.run1();
      }
    }, vm.data.marqueeinterval);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  navgeterDetail(e){
    console.log(e.currentTarget.dataset.id)
    wx.navigateTo({
      url: '/pages/sign/sign?id=' + e.currentTarget.dataset.id,
    })
  },
  addressItem(){
    if(this.data.showIndex==1){
      this.setData({
        showIndex:0
      })
    }else{
      console.log(this.data.quyu)
      this.setData({
        showIndex:1,
        addressDetail: this.data.quyu
      })
    }
    wx.getLocation({
      type: 'wgs84',
      success: (res) => {
        console.log(res)
        wxMap.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude,
          },
          success: (res) => {
            console.log(res.result.ad_info, '逆地址解析');
            var nation = res.result.address_component.nation;
            var province = res.result.address_component.province;
            var city = res.result.address_component.city;
            var district = res.result.address_component.district;
            this.setData({
              diqu: province +'-'+ city +'-'+ district,
              searchValue: res.result.ad_info.adcode
            })
          },
        });
      }
    })
  },
  chooseposition(){
    wx.chooseLocation({
      success: (res) => {
        console.log(res)
        wxMap.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude,
          },
          success: (res)=> {
            console.log(res.result.ad_info, '逆地址解析');
            var nation = res.result.address_component.nation;
            var province = res.result.address_component.province;
            var city = res.result.address_component.city;
            var district = res.result.address_component.district;
            this.setData({
              diqu: province + '-' + city + '-' + district,
              searchValue: res.result.ad_info.adcode
            })
          },
        });
      }
    })
  },
  typeItem(){
    if (this.data.showIndex == 2) {
      this.setData({
        showIndex: 0
      })
    } else {
      console.log(this.data.jobtype)
      this.setData({
        showIndex: 2,
        addressDetail: this.data.jobtype
      })
    }
    console.log(this.data.showIndex)
  },
  salaryItem(){
    if (this.data.showIndex == 3) {
      this.setData({
        showIndex: 0
      })
    } else {
      console.log(this.data.gongzi)
      this.setData({
        showIndex: 3,
        addressDetail: this.data.gongzi
      })
    }
    console.log(this.data.showIndex)
  },
  timeItem(){
    if (this.data.showIndex == 4) {
      this.setData({
        showIndex: 0
      })
    } else {
      this.setData({
        showIndex: 4,
        addressDetail: ['天河',
          '越秀'
        ]
      })
    }
    console.log(this.data.showIndex)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.onLoad();
    setTimeout(function(){
      wx.stopPullDownRefresh;
    },1000)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})